package com.hltx.controller.app.login;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.hltx.controller.base.BaseController;
import com.hltx.pojo.business.BusinessInfo;
import com.hltx.pojo.smscode.SmsCodeValidate;
import com.hltx.pojo.user.User;
import com.hltx.pojo.user.UserLogin;
import com.hltx.service.picture.PictureManager;
import com.hltx.service.smscode.impl.SmsCodeValidateService;
import com.hltx.service.user.UserManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.HttpClientManager;
import com.hltx.util.MD5Util;
import com.hltx.util.MessagesCode;
import com.hltx.util.RegexUtils;
import com.hltx.util.ResultInfo;
import com.hltx.util.sms.code.NeteaseSms;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/app/")
public class AppLoginController extends BaseController {

	@Resource(name = "userService")
	private UserManager userService;

	@Resource(name = "smsCodeValidateService")
	private SmsCodeValidateService smsCodeValidateService;

	@Resource(name = "PictureService")
	private PictureManager PictureService;

	// app用户登录
		@SuppressWarnings("unchecked")
		@RequestMapping(value = "login", method = { RequestMethod.GET, RequestMethod.POST })
		@ResponseBody
		public Map<String, Object> appLogin(HttpServletResponse response, HttpServletRequest request) {
			this.logBefore(logger, "用户登录");
			String userName = request.getParameter("username");
			String pasword = request.getParameter("pwd");
			Map<String, Object> resMap = new HashMap<String, Object>();
			UserLogin login = new UserLogin();
			User use = new User();
			String pasd =pasword;
			use.setUserName(userName);
			use.setPwd(pasd);
			try {
				UserLogin u = userService.getUserMes(use);
				if(u != null){
					if(pasd.equals(u.getPwd())){
				String hxId = userService.getHxId(use);
				if (hxId != null) {
					login.setUserName(hxId);
					User us = userService.appLogin(login);
					if (us.getId() > 0) {
						if ("01".equals(us.getIs_business())) {
							String bid = userService.getBusinessId(us.getId());
							if (bid != null) {
								BusinessInfo bi = userService.getBusiness(bid);
								if (bi != null) {
									resMap.put("merchant", bi);
								}
							}
						}
						if (us.getId() > 0) {
							User user = userService.getAppUser(us.getId());
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "登陆成功"));
							resMap.put("userId", us.getId());
							resMap.put("user", user);
						} else {
							resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "用户不存在!"));
						}
					}
				} else {
					Map<String, Object> userMap = new HashMap<String, Object>();
					String hx = "hltx" + MD5Util.MD5(userName);
					userMap.put("password", /*MD5Util.MD5(*/pasword/*)*/);
					userMap.put("username", hx);
					String appData = HttpClientManager.HxRegister(userMap);
					JSONObject jsonObject = JSONObject.fromObject(appData);
					Map<String, Object> mapJson = JSONObject.fromObject(jsonObject);
					String uri = (String) mapJson.get("uri");
					if (uri != null && !"".equals(uri)) {
						userService.saveAppHx(hx,u.getId());
						String hxI = userService.getHxId(use);
						login.setUserName(hxI);
						User us = userService.appLogin(login);
						if (us.getId() > 0) {
							if ("01".equals(us.getIs_business())) {
								String bid = userService.getBusinessId(us.getId());
								if (bid != null) {
									BusinessInfo bi = userService.getBusiness(bid);
									if (bi != null) {
										resMap.put("merchant", bi);
									}
								}
							}
							if (us.getId() > 0) {
								User user = userService.getAppUser(us.getId());
								resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "登陆成功"));
								resMap.put("userId", us.getId());
								resMap.put("user", user);
							} else {
								resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "用户不存在!"));
							}
						}
					}else{
						resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.LOSE, "注册繁忙稍后重试!"));
					}
				}
					}else{
						resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.NOPWD, "密码错误!"));
					}
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "用户不存在!"));
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
			}
			this.logAfter(logger);
			return resMap;
		}

		@ResponseBody
		@RequestMapping(value = "userRegister", method = { RequestMethod.GET, RequestMethod.POST })
		public Map<String, Object> register(HttpServletResponse response, HttpServletRequest request,
				@Param("code") String urlCode) {
			this.logBefore(logger, "用户注册");
			Map<String, Object> resMap = new HashMap<String, Object>();
			String userName = request.getParameter("phone");
			String pasword = request.getParameter("pwd");
			if(RegexUtils.isMobileNO(userName)){
			String hxId = "hltx" + MD5Util.MD5(userName);
			/*pasword = MD5Util.MD5(pasword);*/
			UserLogin login = new UserLogin();
			login.setPwd(pasword);
			login.setUserName(userName);
			login.setHxId(hxId);
			int id = 0;
			if (validateCode(request)) {
				try {
					int i = userService.findByPhone(login);
					if (i <= 0) {
						try{
						 id = userService.saveUserRegister2(login);
						}catch(Exception e){
							e.printStackTrace();
						}
						if (id > 0) {
							User resultUser = userService.getUserInfo(id);
							if (resultUser != null) {
								resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "注册成功"));
							} else {
								resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "注册出现问题请及时联系"));
							}
						} else if (id == -1) {
							resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.LOSE, "注册繁忙稍后重试!"));
						}
					} else {
						resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.HAVE, "此用户已注册"));
					}
				} catch (Exception e) {
					e.printStackTrace();
					this.logError(logger, e.getMessage());
					resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统异常"));
				}
			} else {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.TEST, "验证码失效"));
			}
			}else{
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.format, "手机号格式不正确"));
			}
			this.logAfter(logger);
			return resMap;
		}
	
	// 验证码验证
			private boolean validateCode(HttpServletRequest request) {
				String phone = request.getParameter("phone");
				String code = request.getParameter("code");
				String types = request.getParameter("type");
				SmsCodeValidate sv = new SmsCodeValidate();
				sv.setPhone(phone);
				sv.setTypes(types);
				sv.setCode(code);
				long lose = 0;
				try {
					SmsCodeValidate date = smsCodeValidateService.getSmsCode(sv);
						String time = date.getExpireTime();
						if (time != null) {
							lose = Long.parseLong(time);
						}
						Long newTime = System.currentTimeMillis();
						if (lose > (newTime / 1000) && date.getSendNum() < 3) {
							return true;
						}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return false;
			}
	// app头像修改
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "saveHeadImage", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> appHeadImage(HttpServletResponse response, HttpServletRequest request) {
		this.logBefore(logger, "头像修改");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String idStr = request.getParameter("id");
		Integer id = null;
		if (idStr != null) {
			id = Integer.parseInt(idStr);
		}
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			System.out.println("ss");
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		// String s = file.getName();
		InputStream in = null;
		try {
			in = file.getInputStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		User user = new User();
		user.setId(id);
		try {
			user = userService.getUser(user);
			String codePre = user.getCodePre();
			String codeSuf = user.getCodeSuf();
			String path = "/personal" + "/" + codePre + id + codeSuf;
			Map imagePath = PictureService.uploadPictureFile(in, path, "userHead.png");
			String imageAddress = (String) imagePath.get("url");
			userService.uploadimageAddress(id, imageAddress);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "头像修改成功"));
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
		}
		return resMap;
	}

	// 发送短信验证码
	@RequestMapping(value = "getCode", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> appSend(HttpServletResponse response, HttpServletRequest request) {
		this.logBefore(logger, "发送短信验证码");
		Map<String, Object> resMap = new HashMap<String, Object>();

		String mobile = request.getParameter("phone");
		String types = request.getParameter("types");
		if (mobile != null) {
			logBefore(logger, mobile);
			// 发送短信
			
			SmsCodeValidate sms = new SmsCodeValidate();
			sms.setPhone(mobile);
			sms.setTypes(types);
			try {
				if( "register".equals(types)){
					User user = new User();
					user.setPhone(mobile);
					String id = userService.getUserByPhone(user);
					if(id != null){
						resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.HAVE, "用户已注册"));
					}else{
						SmsCodeValidate validate = smsCodeValidateService.getSmsData(sms);
						
						if (validate == null) {
						//	Long nowTime = System.currentTimeMillis();
							sms.setExpireTime("60");
							String code = CustomUtil.buildRandom(6) + "";
							sms.setCode(code);
							sms.setSendNum(0);
							resMap.put("code", code);
							int i = smsCodeValidateService.saveSmsCode(sms);
							if (i >= 1) {
								resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "60"));
							} else {
								resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "短信入库异常"));
							}
						
						} else {
							if (Long.valueOf(validate.getExpireTime()) < System.currentTimeMillis()) {
								Long IntervalTime = (long) (validate.getSendNum() < 2 ? 60 : 1800);
								sms.setExpireTime(IntervalTime.toString());
								String code = CustomUtil.buildRandom(6) + "";
								sms.setCode(code);
								sms.setIsUse("00");
								smsCodeValidateService.updateSmsCode(sms);
								resMap.put("code", code);
								resMap.put("result",
										this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, IntervalTime.toString()));
							} else {
								resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, " "));
							}
						}
					}
				}else{
					SmsCodeValidate validate = smsCodeValidateService.getSmsData(sms);
	
					if (validate == null) {
					//	Long nowTime = System.currentTimeMillis();
						sms.setExpireTime("60");
						String code = CustomUtil.buildRandom(6) + "";
						sms.setCode(code);
						sms.setSendNum(0);
						resMap.put("code", code);
						int i = smsCodeValidateService.saveSmsCode(sms);
						if (i >= 1) {
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "60"));
						} else {
							resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "短信入库异常"));
						}
					
					} else {
						if (Long.valueOf(validate.getExpireTime()) < System.currentTimeMillis()) {
							Long IntervalTime = (long) (validate.getSendNum() < 2 ? 60 : 1800);
							sms.setExpireTime(IntervalTime.toString());
							String code = CustomUtil.buildRandom(6) + "";
							sms.setCode(code);
							smsCodeValidateService.updateSmsCode(sms);
							resMap.put("code", code);
							resMap.put("result",
									this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, IntervalTime.toString()));
						} else {
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, " "));
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
			}
		} else {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.HPONE_ISNULL, "手机号码不能为空!"));
		}
		this.logAfter(logger);
		return resMap;
	}

	@RequestMapping(value = "send", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> send(HttpServletResponse response,HttpServletRequest request){
		this.logBefore(logger, "发送短信验证码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String mobile = request.getParameter("userName");
		if(mobile != null){
			logBefore(logger, mobile);
			//发送短信
			SmsCodeValidate sms = new SmsCodeValidate();
			sms.setPhone(mobile);
			sms.setTypes(request.getParameter("type"));
			try {
				SmsCodeValidate validate = smsCodeValidateService.getSmsData(sms);
				if(validate == null){
				//	Long nowTime= System.currentTimeMillis() ;
					sms.setExpireTime("60");
					String code =CustomUtil.buildRandom(6)+"";
					sms.setCode(code);
					sms.setSendNum(0);
					//发送短信线程
					resMap.put("code", code);
					resMap.put("sendNum", 0);
					int i= smsCodeValidateService.saveSmsCode(sms);
					if(i>=1){
						NeteaseSms.sendTemplateSms(mobile, code);
						resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "60"));
					}else{
						resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "短信入库异常"));
					}
				}else{
					SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); 
					String date = format.format(new Date());
					String date_time= validate.getCreateTime();
					date_time = date_time.substring(0, 10).replace("-", "").trim();
					if (validate.getSendNum()>=10 && !date.equals(date_time)) {
						validate.setSendNum(-1);
						smsCodeValidateService.intiSmsData(validate);
					}
					if (validate.getSendNum()<10) {
						if (Long.valueOf(validate.getExpireTime()) < System.currentTimeMillis()) {
							Long IntervalTime = (long) (validate.getSendNum()<2?60:1800);
							sms.setExpireTime(IntervalTime.toString());
							String code =CustomUtil.buildRandom(6)+"";
							sms.setCode(code);
							smsCodeValidateService.updateSmsCode(sms);
							NeteaseSms.sendTemplateSms(mobile, code);
							resMap.put("code", code);
							resMap.put("sendNum", validate.getSendNum());
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, IntervalTime.toString()));
						}else{
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, " "));
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		}else{
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.HPONE_ISNULL, "手机号码不能为空!"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "unLoginForgetPwd", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> appUpdatePwd(HttpServletResponse response, HttpServletRequest request) {
		this.logBefore(logger, "修改密码");
		String pwd = request.getParameter("pwd");
		String phone = request.getParameter("phone");
		String code = request.getParameter("code");
		String confirmPwd = request.getParameter("confirmPwd");
		Map<String, Object> resMap = new HashMap<String, Object>();
//		pwd = MD5Util.MD5(pwd);
		/*confirmPwd = MD5Util.MD5(confirmPwd);*/
		User user = new User();
		user.setPwd(pwd);
		user.setPhone(phone);
		user.setUserName(phone);
		user.setTypes("password");
		try {
			if (validateCode(request)) {
				if (pwd.equals(confirmPwd)) {
					String co = userService.getAppCode(user);
					if (code.equals(co)) {
						User us = userService.getLoginId(user);
						if (us != null) {
							Map<String, Object> nmap = new HashMap<>();
							nmap.put("newpassword", pwd);
							user.setPwd(us.getPwd());
							String hxId = userService.getHxId(user);
							if (hxId != null) {
								String massage = HttpClientManager.updateHxPwd(hxId, nmap);
								JSONObject jsonO = JSONObject.fromObject(massage);
								Map<String, Object> mapJson = JSONObject.fromObject(jsonO);
								String action = (String) mapJson.get("action");
								if (action != null && action != "") {
									user.setPwd(pwd);
									userService.updateAppPwd(user);
									//String newPwd = userService.getPwd(user);
									resMap.put("result",
											this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "密码修改成功"));
								} else {
									resMap.put("result",
											this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "环信重置密码失败!"));
								}
							} else {
								resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "用户不存在!"));
							}
						} else {
							resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "用户不存在!"));
						}
					}
				} else {
					resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.RESET, "两次密码输入不匹配!"));
				}
			} else {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.TEST, "验证码有误!"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	// 发送短信验证码
		@RequestMapping(value = "getUserInfo", method = { RequestMethod.GET, RequestMethod.POST })
		@ResponseBody
		public Map<String, Object> getUserInfo(HttpServletResponse response, HttpServletRequest request) {
			this.logBefore(logger, "查询用户信息");
			Map<String, Object> resMap = new HashMap<String, Object>();
			String idStr = request.getParameter("id");
			int id = Integer.parseInt(idStr);
			try {
				User user = userService.getAppUser(id);
				if("01".equals(user.getIs_business())){
					String bid = userService.getBusinessId(id);
					BusinessInfo bi = userService.getBusiness(bid);
					if(bi != null){
						resMap.put("merchant", bi);
					}
				}
				resMap.put("userInfo", user);
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
			}
			this.logAfter(logger);
			return resMap;
		}
	
}
